'''
该程序说明：使用点亮一颗 LED
在线文档：https://docs.geeksman.com/esp32/MicroPython/04.esp32-micropython-LED.html
'''
import time
from machine import Pin, ADC, SoftI2C
from setting import *
from lib.sh1106 import SH1106, SH1106_I2C
import time
 
 

 
i2c = SoftI2C(scl=Pin(POWER_PIN_OLED_I2C_SCL), sda=Pin(POWER_PIN_OLED_I2C_SDA), freq=800000)
oled = SH1106_I2C(128, 64, i2c, None, 0x3c)
 
ps1_button = Pin(POWER_PIN_PS1_Z, Pin.IN)
ps1_x = ADC(Pin(POWER_PIN_PS1_X), atten=ADC.ATTN_11DB)
ps1_y = ADC(Pin(POWER_PIN_PS1_Y), atten=ADC.ATTN_11DB)


ps2_button = Pin(POWER_PIN_PS2_Z, Pin.IN)
ps2_x = ADC(Pin(POWER_PIN_PS2_X), atten=ADC.ATTN_11DB)
ps2_y = ADC(Pin(POWER_PIN_PS2_Y), atten=ADC.ATTN_11DB)


 # Screen size
width=128
height=64 # we could make this be 63 but the init method should use the full value
# oled = SSD1306_I2C(width, height, i2c)
 

oled.fill(0) # clear to black

# note that OLEDs have problems with screen burn it - don't leave this on too long!
def border(width, height):
    oled.hline(0, 0, width - 1, 1) # top edge
    oled.hline(0, height - 2, width - 1, 1) # bottom edge
    oled.vline(0, 0, height - 1, 1) # left edge
    oled.vline(width - 1, 0, height - 1, 1) # right edge

# ok, not really a circle - just a square for now
def draw_ball(x,y, size, state):
    if size == 1:
         oled.pixel(int(x-size/2) + i, int(y-size/2) + j, state) # draw a single pixel
    else:
        for i in range(0,size): # draw a box of pixels of the right size
            for j in range(0,size):
                oled.pixel(int(x-size/2) + i, int(y-size/2) + j, state)
    # TODO: for size above 4 round the corners

border(width, height)

ball_size = 10
ball_size2 =15
current_x = int(width / 2)
current_y = int(height / 2)
direction_x = 1
direction_y = -1
# delay_time = .0001


while True:
  print("--")
#   oled.fill(0)
  border(width, height)
#   print(ps2_button.value())
  time.sleep(0.02)
#   print(pin2.value())
#   time.sleep(0.2)
  print(f'PS1_X:{ps1_x.read()},PS1_Y:{ps1_y.read()},z:{ps1_button.value()} | PS2_X:{ps2_x.read()},PS2_Y:{ps2_y.read()},z:{ps2_button.value()} ')
  
  x1 = int((width/2 ) * ( ps1_x.read() - 2000 )  / 2000 + width/2)
  y1 = int((height/2 ) * ( ps1_y.read() - 2000 ) *1/2000 + height/2)
  x2 = int((width/2 ) * ( ps2_x.read() - 2000 )  / 2000 + width/2)
  y2 = int((height/2 ) * ( ps2_y.read() - 2000 ) *1/2000 + height/2)
  
  
  draw_ball(x1,y1, ball_size,1)
  draw_ball(x2,y2, ball_size2,1)
  oled.show()
  # utime.sleep(delay_time)
  draw_ball(x1,y1,ball_size,0)
  draw_ball(x2,y2,ball_size2,0)
    